<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert title="添加商品信息" type="info" show-icon center :closable="false">
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center="">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form ref="addFormRef" :model="add_form" :rules="rules" label-width="80px" label-position="top">
        <el-tabs v-model="activeIndex" tab-position="left" style="height: 100%;" :before-leave="beforeLeaveTab" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="add_form.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="add_form.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="add_form.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="add_form.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="selectCatId" :options="classlist" :props="{ expandTrigger: 'hover', label:'cat_name', value:'cat_id' }" @change="classAddChange" clearable></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item1 in manyData" :key="item1.attr_id" :label="item1.attr_name">
              <el-checkbox-group v-model="item1.attr_vals">
                <el-checkbox v-for="(item2,index) in item1.attr_vals" :key="index" :label="item2" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload action="http://127.0.0.1:8888/api/private/v1/upload" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture" :headers="headersObj" :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor ref="myQuillEditor" v-model="add_form.goods_introduce" />
            <el-button type="primary" @click="addGoods" class="addBtn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!-- 图片预览区域 -->
      <el-dialog title="预览" :visible.sync="dialogVisible" width="50%">
        <img :src="previewPath" alt="" class="previewImg">
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'MyAdd',
  data() {
    return {
      activeIndex: '0',
      classlist: [],
      selectCatId: [],
      manyData: [],
      onlyData: [],
      add_form: {
        goods_name: '',
        goods_cat: '',
        goods_price: '',
        goods_number: '',
        goods_weight: '',
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      previewPath: '',
      dialogVisible: false,
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      rules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }]
      }
    }
  },
  // 计算属性
  computed: {
    // 当前选中的三级分类的Id
    classId() {
      if (this.selectCatId.length === 3) {
        return this.selectCatId[2]
      }
      return null
    }
  },
  created() {
    this.getClassList()
  },
  methods: {
    // 获取商品分类数据列表
    async getClassList() {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据列表失败！')
      }
      this.classlist = res.data
    },
    // 将已选择分类项的id值数组转换为字符串，存入添加表单中
    classAddChange() {
      // console.log(this.selectCatId)
      if (this.selectCatId.length !== 3) {
        this.selectCatId = []
      } else {
        this.add_form.goods_cat = this.selectCatId.join(',')
        // console.log(this.add_form)
      }
    },
    beforeLeaveTab(activeIndex, oldactiveIndex) {
      if (oldactiveIndex === '0' && this.selectCatId.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    // 获取当前分类下商品的参数
    async tabClicked() {
      if (this.activeIndex === '1') {
        // 根据所选分类的Id，和当前所处的面板，获取对应的参数
        const { data: res } = await this.$http.get('/categories/' + this.classId + '/attributes', { params: { sel: 'many' } })
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数列表失败！')
        }
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.manyData = res.data
        // console.log(this.manyData)
      } else if (this.activeIndex === '2') {
        // 根据所选分类的Id，和当前所处的面板，获取对应的参数
        const { data: res } = await this.$http.get('/categories/' + this.classId + '/attributes', { params: { sel: 'only' } })
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数列表失败！')
        }
        this.onlyData = res.data
        // console.log(this.onlyData)
      }
    },
    // 处理图片预览效果
    handlePreview(file) {
      // console.log(file)
      this.previewPath = file.response.data.url
      this.dialogVisible = true
    },
    // 上传图片成功
    handleSuccess(res) {
      // console.log(res)
      // 1. 拼接得到一个图片信息对象
      const picInfo = { pic: res.data.tmp_path }
      // 2. 将图片信息对象，push 到pics数组中
      this.add_form.pics.push(picInfo)
      // console.log(this.add_form.pics)
    },
    // 处理删除图片操作
    handleRemove(file) {
      // console.log(file)
      // 1. 获取将要删除的图片的临时路径
      const filePath = file.response.data.tmp_path
      // 2. 从 pics 数组中，找到这个图片对应的索引值
      const index = this.add_form.pics.findIndex(item => item.pic === filePath)
      // 3. 调用数组的 splice 方法，把图片信息对象，从 pics 数组中移除
      this.add_form.pics.splice(index, 1)
      // console.log(this.add_form.pics)
    },
    // 添加商品
    addGoods() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请完整填写表单')
        } else {
          // 处理动态参数
          this.manyData.forEach(item => {
            const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') }
            this.add_form.attrs.push(newInfo)
          })
          // 处理静态属性
          this.onlyData.forEach(item => {
            const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
            this.add_form.attrs.push(newInfo)
          })
          // console.log(this.add_form)
          const { data: res } = await this.$http.post('/goods', this.add_form)
          if (res.meta.status !== 201) {
            return this.$message.error('添加商品失败')
          }
          this.$message.success('添加商品成功')
          this.$router.push('/goods')
        }
      })
    }
  }
}
</script>

<style lang='less' scoped>
.el-cascader {
  width: 260px;
}
.el-checkbox {
  margin: 0;
  margin-left: 10px;
}
.previewImg {
  width: 100%;
}
.addBtn {
  margin-top: 15px;
}
</style>
